import { history } from 'umi';
import { extend, RequestOptionsInit } from 'umi-request';

import { message } from 'antd';

const codeMessage = {
  200: '服务器成功返回请求的数据。',
  201: '新建或修改数据成功。',
  202: '一个请求已经进入后台排队（异步任务）。',
  204: '删除数据成功。',
  400: '发出的请求有错误，服务器没有进行新建或修改数据的操作。',
  401: '用户没有权限（令牌、用户名、密码错误）。',
  403: '用户得到授权，但是访问是被禁止的。',
  404: '发出的请求针对的是不存在的记录，服务器没有进行操作。',
  405: '请求方法不被允许。',
  406: '请求的格式不可得。',
  410: '请求的资源被永久删除，且不会再得到的。',
  422: '当创建一个对象时，发生一个验证错误。',
  500: '服务器发生错误，请检查服务器。',
  502: '网关错误。',
  503: '服务不可用，服务器暂时过载或维护。',
  504: '网关超时。',
};

/**
 * 异常处理程序
 */
const errorHandler = (error: any) => {
  console.info('errorHandler', error);
  const { response, data } = error;
  console.log(response, data);
  if (response && response?.status) {
    // @ts-ignore
    const errorText = codeMessage[response?.status] || response?.statusText;

    message.error(errorText);
  }

  if (!response && !data) {
    message.error('哇哦，服务器出错啦，请稍候再试~');
  } else if (data) {
    message.error(data?.ret?.msg);
  }
};

// 请求拦截
const authHeaderInterceptor = (url: string, options: RequestOptionsInit) => {
  // const authHeader = { Authorization: 'Bearer xxxxxx' };// 配置统一token使用
  // 判断是否有 token
  const token = localStorage.getItem('token');
  if (token) {
    return {
      url,
      options: {
        ...options,
        interceptors: true,
        headers: {
          ...options.headers,
          terminal: 101,
          Authorization: `Bearer ${token}`,
        },
      },
    };
  }
  return { url, options };
};
// 响应后拦截
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const demoResponseInterceptors = async (
  response: Response,
  options: RequestOptionsInit,
) => {
  let response1 = response.clone();
  // response1.json()
  //   let {body} = response
  response1.json().then((res) => {
    //  console.log(new Date(), response.url, res);

    // eslint-disable-next-line eqeqeq
    if (res.status === 402 || res.status === 406) {
      localStorage.removeItem('token');
      // @ts-ignore
      //  const { query } = history.location;

      history.replace('/login');
    }
    return res;
  });
  return response;
};
//
// function getToken() {
//   return localStorage.getItem('token') || '';
// }

function createClient(baseUrl: string) {
  const request = extend({
    prefix: baseUrl,

    requestInterceptors: [authHeaderInterceptor],
    responseInterceptors: [demoResponseInterceptors],
    errorHandler,
  });

  request.interceptors.request.use((url: string, options: any) => {
    const token = localStorage.getItem('token');
    if (token) {
      return {
        url,
        options: {
          ...options,
          interceptors: true,
          headers: {
            ...options.headers,
            'Content-Type': 'application/json',
            terminal: 101,
            Authorization: `${token}`,
          },
        },
      };
    }
    return {
      url,
      options: {
        ...options,
        interceptors: true,
        headers: {
          ...options.headers,
          'Content-Type': 'application/json',
          terminal: 101,
          Authorization: ``,
        },
      },
    };
  });
  // request拦截器, 改变url 或 options.
  /*  request.interceptors.request.use ((url, options) =>{
      let token = localStorage.getItem('token');
      if (null === token) {
        token = '';
      }
      const version = '1.0.0';
      const lang = "zh-CN";
      const authHeader = {
        Authorization: `${token}`,
        Version: version,
        MyLanguage: `${lang}`,
        'Content-Type': 'application/json',
        Accept: 'application/json',
        terminal: 1
      };
      return {
        url: url,
        options: { ...options, interceptors: true, headers: authHeader },
      };
    }, { synchronous: true});*/

  request.interceptors.response.use(demoResponseInterceptors);

  return request;
}

function createClientData(baseUrl: string) {
  function post<T>(url: string, params: object) {
    return new Promise<API.Result<T>>((resolve, reject) => {
      createClient(baseUrl)
        .post<API.Result<T>>(url, { data: { ...params }})
        .then((res) => {
          resolve(res);
        })
        .catch((err) => {
          reject(err);
        });
    });
  }
  function postParam<T>(url: string, params: object) {
    return new Promise<API.Result<T>>((resolve, reject) => {
      createClient(baseUrl)
        .post<API.Result<T>>(url, { params: { ...params }})
        .then((res) => {
          resolve(res);
        })
        .catch((err) => {
          reject(err);
        });
    });
  }
  function get<T>(url: string, params: any = {}) {
    return new Promise<T>((resolve, reject) => {
      createClient(baseUrl)
        .get<API.Result<T>>(url, { params: { ...params } })
        .then((res) => {
          console.log('res', res);
          if (res) {
            if (res.status === 200) {
              // @ts-ignore
              resolve(res.data);
            } else {
              reject(res);
            }
          }
        })
        .catch((err) => {
          reject(err);
        });
    });
  }

  function getList<T>(url: string, params: any = {}) {
    return new Promise<API.BaseArrayDataResult<T>>((resolve, reject) => {
      createClient(baseUrl)
        .get<API.BaseArrayDataResult<T>>(url, { params: { ...params } })
        .then((res) => {
          if (res) {
            if (res.status === 200) {
              resolve(res);
            } else {
              reject(res);
            }
          }
        })
        .catch((err) => {
          reject(err);
        });
    });
  }

  return {
    post,
    postParam,
    get,
    getList,
  };
}

export const oauthRequest = createClientData('/api/oauth/');
export const sysRequest = createClientData('/api/sys/');
export const userRequest = createClientData('/api/users/');
export const messagesRequest = createClientData('/api/messages/');
export const cdnRequest = createClientData('/api/cdn/');
export const orgRequest = createClientData('/api/org/');
export const actRequest = createClientData('/api/act/');
export const shopRequest = createClientData('/api/shop/');
export const apiRequest = createClientData('/api/');
export const baseRequest = createClientData('/');

export const goodsRequest = createClientData('/api/goods/');
export const advertisingRequest = createClientData(
  '/api/advertisingManagement/',
);
export const agentRequest = createClientData('/api/agent/');
export const posterRequest = createClientData('/api/poster/');
export const orderRequest = createClientData('/api/order/');
export const cloudOrderRequest = createClientData('/api/cloud/order/');
export const stasticaRequest = createClientData('/api/stastica/');
export const couponRequest = createClientData('/api/coupon/');
export const taocanRequest = createClientData('/api/taocan/');
export const videoRequest = createClientData('/api/video/');
